<?php
require_once("inc.member.php");

$this_title="$vars[member_title] &raquo; ".__("Commission Report");
$page_title=__("Commission Report");
$content_title=__("Commission Report");

$item_per_page=$vars["user_item_per_page"];
$td_width=180;

$r_status=array("confirmed","cancelled");
$r_status_d=array("confirmed"=>__("Confirmed"),"cancelled"=>__("Cancelled"));
$r_comm_type=array('s','p','l');
$r_type=array('summary','s','p','l');
if($r_user['is_stockist'] == 'y'){
	$r_comm_type[] = 't';
	$r_type[] = 't';
}
$r_type_d=array('summary'=>__("Summary"),'s'=>__("Sponsor Commission"),'p'=>__("Pairing Commission"),'l'=>__("Matching Commission"));
$r_month=array('1','2','3','4','5','6','7','8','9','10','11','12');
$r_month_d=array('1'=>__("1"),'2'=>__("2"),'3'=>__("3"),'4'=>__("4"),'5'=>__("5"),'6'=>__("6"),'7'=>__("7"),'8'=>__("8"),'9'=>__("9"),'10'=>__("10"),'11'=>__("11"),'12'=>__("12"));
for($i=2009,$j=0,$t=ndate("Y");$i<=$t;$i++){
 $r_year[$j++]=$i;
 $r_year_d[$i]=$i;
}

if(!$get_s['type']){
	$view_type = 'summary';
}else{
	$view_type = $get_s['type'];
}

if($view_type == 'summary'){
	$k = 0;
	//date range
	$date_q = "";
	if($get_s['date_from']<>'' && $get_s['date_to']<>''){
		$date_q = " and bonus_date between '".$get_s['date_from']."' and '".$get_s['date_to']."' ";
	}elseif($get_s['date_from']<>''){
		$date_q = " and bonus_date >= '".$get_s['date_from']."' ";
	}elseif($get_s['date_to']<>''){
		$date_q = " and bonus_date <= '".$get_s['date_to']."' ";
	}
	
	foreach($r_comm_type as $type){
		if($type == 'm'){
			$comm[$type]['total'] = mysql_result(mysql_query($sum_sql="select sum(amount2) from $db->member_comm where uid='$uid' and type='$type' and status='confirmed'".$date_q), 0) or 0;
		}else{
			$comm[$type]['total'] = mysql_result(mysql_query($sum_sql="select sum(amount) from $db->member_comm where uid='$uid' and type='$type' and status='confirmed'".$date_q), 0) or 0;
		}
		
		$comm[$type]['times'] = mysql_result(mysql_query($count_sql="select count(*) from $db->member_comm where uid='$uid' and type='$type' and status='confirmed'".$date_q), 0) or 0;
		$comm[$type]['last'] = @mysql_result(mysql_query($date_sql="select cdate from $db->member_comm where uid='$uid' and type='$type' and status='confirmed' ".$date_q." order by cdate desc limit 1"), 0) or 0;
		$comm_sum_row .= "
		<tr class='row$k'>
			<td>{$r_type_d[$type]}</td>
			<td>".(!$comm[$type]['last']? '-' : date($vars['date_format'], strtotime($comm[$type]['last'])))."</td>
			<td class='right'>{$comm[$type]['times']}</td>
			<td class='right'>".number_format($comm[$type]['total'], 2)."</td>
		</tr>";
		$k = 1 - $k;
		$comm_total += $comm[$type]['total'];
	}
	$main_total = @mysql_result(mysql_query($sql="select sum(amount) from $db->member_maintain where uid in ($uid) ".$date_q), 0) or 0;
	
	$comm_list = "
	<table class='pbl_table'>
		<tr class='pbl_header'>
			<td class='left'>".__('Commission')."</td>
			<td class='left'>".__('Last Paid Date')."</td>
			<td class='right'>".__('No. of Times')."</td>
			<td class='right'>".__('Amount')." ($vars[currency])</td>
		</tr>
		$comm_sum_row
		<tr class='pbl_header'>
			<td colspan='3' style='text-align:right;'>".__('Total Bonus').":</td>
			<td class='right'>".number_format($comm_total, 2)."</td>
		</tr>
	</table>";
}else{
	//#####COMMISSION GET#####
	if($_GET["__req"]){
		//ERROR CHECK
		if(!in_array($get_s["type"], $r_type)){
			$errmsg.=__("Please select a commission first.")."<br />\n";
		}
		if($get_s['date_from'] && $get_s['date_to'] && strtotime($get_s['date_from']) > strtotime($get_s['date_to'])){
			$errmsg.=__("The selected Date From is greater than the Date To.")."<br />\n";
		}

		if(!$errmsg){
			$comm_query = true;

			//date range
			$date_q = "";
			if($get_s['date_from']<>'' && $get_s['date_to']<>''){
				$date_q = " and bonus_date between '".$get_s['date_from']."' and '".$get_s['date_to']."' ";
			}elseif($get_s['date_from']<>''){
				$date_q = " and bonus_date >= '".$get_s['date_from']."' ";
			}elseif($get_s['date_to']<>''){
				$date_q = " and bonus_date <= '".$get_s['date_to']."' ";
			}

			if($get_s['type'] == 'main'){
				$count_sql="select count(*) from $db->member_maintain where uid in ($uid) $date_q";
				$sum_sql="select sum(amount) from $db->member_maintain where uid in ($uid) $date_q";
				$record_sql="select * from $db->member_maintain where uid in ($uid) $date_q order by year desc, month desc, cdate desc limit <%limit_start%>, <%limit%>";
				$maintain_total = @mysql_result(mysql_query($sum_sql), 0) or 0;
				$grand_total = $maintain_total;
			}else{
				$count_sql="select count(*) from $db->member_comm where uid='$uid' and type='$get_d[type]' and status='confirmed' $date_q";
				if($get_d['type'] == 'm'){
					$sum_sql="select sum(amount2) from $db->member_comm where uid='$uid' and type='$get_d[type]' and status='confirmed' $date_q";
				}else{
					$sum_sql="select sum(amount) from $db->member_comm where uid='$uid' and type='$get_d[type]' and status='confirmed' $date_q";
				}
				$record_sql="select b.code, a.* from $db->member_comm a left join $db->users b on b.id=a.from_uid where a.uid='$uid' and a.type='$get_d[type]' and a.status='confirmed' $date_q order by a.bonus_date limit <%limit_start%>, <%limit%>";
			}
			
			$cur_page=$_GET["nav"];
			$total_record=@mysql_result(mysql_query($count_sql), 0);
			$total_page=ceil($total_record/$item_per_page);
			$page=($cur_page? ($cur_page>$total_page? $total_page : ($cur_page<1? 1 : $cur_page)) : 1);
			$limit_start=($page-1)*$item_per_page;
			$nav_link=format_page_admin($page, $total_page, $this_file);
			$this_page_total=@mysql_num_rows($r=mysql_query(str_replace("<%limit_start%>", $limit_start, str_replace("<%limit%>", $item_per_page, $record_sql))));
			$grand_total = @mysql_result(mysql_query($sum_sql), 0) or 0;
			$k=0;
			for($i=0;$i<$this_page_total;$i++){
				$comm=mysql_fetch_assoc($r);
				$this_no = ($page - 1) * $item_per_page + $i + 1;
				//maintenance
				if($get_s['type']=='main'){
					$comm_row.="
					<tr class='row$k'>
						<td width=20>".$this_no."</td>
						<td>".__("Contribution to Maintenance")."</td>
						<td>".$r_type_d[$comm["comm_type"]]."</td>
						<td class='number'>".number_format($comm["amount"], 2)."</td>
						<td class='number'>".$comm["percent"]."</td>
						<td>".date('M Y', mktime(0, 0, 0, $comm["month"], 1, $comm["year"]))."</td>
					</tr>";
				}else{
					if($comm['type'] == 's'){						$comm_desc = replace_tag(__("Sponsor Bonus received from downline ID#<%from_uid%>. Percentage:<%percent%>. Commission Payable For:<%bonus_date%>"), (array("<%from_uid%>"=>$comm['code'], "<%percent%>"=>$comm['percent'], "<%bonus_date%>"=>$comm['bonus_date'])));					}elseif($comm['type'] == 'p'){						$comm_desc = replace_tag(__("Pairing Bonus received from downline ID#<%from_uid%>. Paired:<%volume_type%>BV. Percentage:<%percent%>. Rate:<%percent2%>. Commission Payable For: <%bonus_date%>"), (array("<%from_uid%>"=>$comm['code'], "<%percent%>"=>$comm['percent'], "<%percent2%>"=>$comm['percent2'], "<%volume_type%>"=>number_format($comm['volume_type'],0), "<%bonus_date%>"=>$comm['bonus_date'])));					}elseif($comm['type'] == 'l'){						$comm_desc = replace_tag(__("Leadership Bonus received from downline ID#<%from_uid%> for pairing bonus. Pairing Amount:<%volume_type%>. Level:<%level%>. Percentage: <%percent%>. Commission Payable For: <%bonus_date%>"), (array("<%from_uid%>"=>$comm['code'], "<%percent%>"=>$comm['percent'], "<%level%>"=>$comm['level'], "<%volume_type%>"=>number_format($comm['volume_type'],0), "<%bonus_date%>"=>$comm['bonus_date'])));					}
					$comm_row.="
					<tr class='row$k'>
						<td class='left'>".$this_no."</td>
						<td class='left'>".$comm_desc."</td>
						<td class='left'>".date($vars['date_format'], strtotime($comm['cdate']))."</td>
						<td class='right'>".number_format(($comm['type'] == 'm' && ($comm['year'] * 12 + $comm['month']) >= (2009 * 12 + 11))? $comm['amount2'] : $comm['amount'], 2)."</td>
					</tr>";
					$k=1-$k;
				}
			}

			//listing text
			$listing_text=replace_tag(__("Listing <%x%> <%comm%>."), array("<%x%>"=>strval($total_record), "<%comm%>"=>$total_record>1? __("commissions") : __("commission")));

			//comm header
			if($get_s['type'] == 'main'){
				$header_row = "
				<tr class='pbl_header'>
					<td>".__("Trans#")."</td>
					<td>".__("Maintenance")."</td>
					<td>".__("From Commission")."</td>
					<td>".__("Amount")."</td>
					<td>".__("Percent")."</td>
					<td>".__("Date")."</td>
				</tr>";
			}else{
				$header_row = "
				<tr class='pbl_header'>
					<td class='left'>".__("Trans#")."</td>
					<td class='left'>".__("Description")."</td>
					<td class='left' width='125'>".__("Paid Date")."</td>
					<td class='right' width='80'>".__("Amount")." ($vars[currency])</td>
				</tr>";
			}
			
			//listing
			$comm_list=
			"<h3>".replace_tag(__("<%title%> Total: <%x%>"), array("<%title%>"=>$r_type_d[$get_s["type"]], "<%x%>"=>number_format($grand_total, 2)))."</h3>
			$listing_text $nav_link
			<table class='pbl_table'>
				$header_row
				$comm_row
			</table>";
		}
	}

	$errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
}
//#####END COMMISSION GET#####

$form_fields=array("type"=>"summary");
foreach($form_fields as $field => $default){
 $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
 $dis[$field]=(!$get_s["__req"]? $default : $get_h[$field]);
}
$type_select=build_select($r_type, $r_type_d, $dis["type"], "type");

//javascript
ob_start();
?>
<script type='text/javascript' src='<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js,jquery.datepicker.js"); ?>'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
	j('select[@name=type]').change(function(){
		j('form[@name=comm_form]').submit();
	});
	
	<?php #datepicker ?>
	j('#date_from').datepicker({
		changeMonth: true,
		changeYear: true,
		dateFormat: 'yy-mm-dd',
		minDate: new Date(2009,4,1), 
		maxDate: '+1M +10D'
	});
	j('#date_to').datepicker({
		changeMonth: true,
		changeYear: true,
		dateFormat: 'yy-mm-dd',
		minDate: new Date(2009,4,1), 
		maxDate: '+1M +10D'
	});
});
</script>
<?php
$jvscript = ob_get_clean();

//css
ob_start();
?>
<link rel="stylesheet" href="<?php echo CSS_URL; ?>/jstheme/ui-lightness/jquery-ui.css" type="text/css" />
<?php
$css .= ob_get_contents();
ob_end_clean();

$comm_ui=($errmsg || $msg? $errmsg.$msg : "").
"<form name='comm_form' method='get' action='$this_file'>
<input type='hidden' name='__req' value='1' />
<input type='hidden' name='nav' value=\"$get_h[nav]\" />
<table class='pbt_table'>
	<tr>
		<td>".__("Commission").__(":")." $type_select</td>
	</tr>
	<tr>
		<td>".__("From").__(":")." <input type='text' name='date_from' id='date_from' value=\"$get_h[date_from]\" />
		".__("To").__(":")." <input type='text' name='date_to' id='date_to' value=\"$get_h[date_to]\" /> <input type='submit' value=\"".__("Generate")."\" /></td>
	</tr>
</table>
</form>";

$content="<h2>$page_title</h2>$comm_ui$comm_list";

print format_member_page($content, $this_title, $content_title, $css.$jvscript);
?>